import { defineStore } from 'pinia'
import { ref } from 'vue'
import UserService from '@/api/user'
import { constantRoutes } from '@/router'
import { resetRouter } from '@/router'

//用户模块 token setToken removeToken
export const useUserStore = defineStore(
  'user',
  () => {
    // token部分
    const token = ref('')
    const setToken = (newToken: any) => {
      token.value = newToken
    }
    const removeToken = () => {
      token.value = ''
    }

    // user部分
    const user = ref({} as any)
    const getUser = async () => {
      const res = await UserService.userGetInfoService() // 请求获取数据
      console.log('正在请求用户信息')
      user.value = res
    }
    const setUser = (obj: any) => {
      user.value = obj
    }

    // 退出，清除token、用户信息、重置路由
    const logout = () => {
      removeToken()
      setUser({})
      resetRouter()
    }

    // 动态路由
    const isRefreshRouter = ref(false)
    const routes = ref([...constantRoutes])
    const setRoutes = (newRoutes: any[]) => {
      routes.value = [...constantRoutes, ...newRoutes] // 静态路由 + 动态路由
    }

    // 定义好的仓库要暴露出去属性、方法
    return {
      token,
      setToken,
      removeToken,
      user,
      getUser,
      setUser,
      logout,
      routes,
      isRefreshRouter,
      setRoutes
    }
  },
  {
    persist: true //持久化
  }
)
